import type {ProColumns} from '@ant-design/pro-components';
import {ActionType, PageContainer} from '@ant-design/pro-components';
import {Button, message, Popconfirm} from 'antd';
import {useRef, useState} from 'react';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import DetailModal from './components/DetailModal';
import ProTable from '@ant-design/pro-table';
import {addStudentAPI, deleteStudentAPI, pageStudentAPI, updateStudentAPI} from "@/pages/student-manager/services";
import {listLicenseTypeAPI} from "@/pages/license-type/services";

const StudentManager = () => {
  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
  const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
  const [detailModalVisible, setDetailModalVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<API.IStudent>();
  const actionRef = useRef<ActionType>();
  const [loading, setLoading] = useState<boolean>(false);

  const columns: ProColumns<API.IStudent>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      hideInSearch: true,
    },
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '报名类型',
      dataIndex: 'enrollmentType',
      request: async () => {
        const {data} = await listLicenseTypeAPI({});
        console.log('data', data)
        return (data || []).map((item: API.ILicenseType) => {
          return {
            label: item.licenseCode,
            value: item.licenseCode,
          }
        })
      },
    },
    {
      title: '学籍状态',
      dataIndex: 'learningStatus',
      valueEnum: {
        1: '在籍',
        2: '休学',
        3: '退学',
        4: '毕业',
      }
    },
    {
      title: '理论成绩',
      dataIndex: 'theoryScore',
      hideInSearch: true,
    },
    {
      title: '路考成绩',
      dataIndex: 'drivingScore',
      hideInSearch: true,
    },
    {
      title: '操作',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="detail"
          onClick={() => {
            setCurrentRow(record);
            setDetailModalVisible(true);
          }}
        >
          详情
        </a>,
        <a
          key="update"
          onClick={() => {
            setCurrentRow(record);
            setUpdateModalVisible(true);
          }}
        >
          编辑
        </a>,
        <Popconfirm
          key="delete"
          title="确定要删除吗？"
          onConfirm={async () => {
            const {data} = await deleteStudentAPI(record.id)
            if (data) {
              message.success('删除成功');
              actionRef.current?.reload();
            }
          }}
        >
          <a style={{color: 'red'}}>删除</a>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.IStudent>
        headerTitle="学员列表"
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        actionRef={actionRef}
        size={'small'}
        toolBarRender={() => [
          <Button
            key="add"
            type="primary"
            onClick={() => {
              setCreateModalVisible(true);
            }}
          >
            新增学员
          </Button>,
        ]}
        request={async (params) => {
          // 实际项目中替换为API调用
          const {data} = await pageStudentAPI(params);
          return data
        }}
        columns={columns}
        loading={loading}
        pagination={{
          pageSize: 10,
        } as any}
      />

      {/* 创建表单 */}
      <CreateForm
        visible={createModalVisible}
        onVisibleChange={setCreateModalVisible}
        onFinish={async (values: API.IStudent) => {
          const {data} = await addStudentAPI(values)
          if (data) {
            message.success('创建成功');
            actionRef.current?.reload();
            setCreateModalVisible(false);
          }
        }}
      />

      {/* 更新表单 */}
      {currentRow && (
        <UpdateForm
          visible={updateModalVisible}
          onVisibleChange={setUpdateModalVisible}
          values={currentRow}
          onFinish={async (values) => {
            const {data} = await updateStudentAPI({...values, id: currentRow.id, version: currentRow.version})
            if (data) {
              message.success('修改成功');
              actionRef.current?.reload();
              setUpdateModalVisible(false);
            }
          }}
        />
      )}

      {/* 详情模态框 */}
      {currentRow && (
        <DetailModal
          visible={detailModalVisible}
          onVisibleChange={setDetailModalVisible}
          values={currentRow}
        />
      )}
    </PageContainer>
  );
};

export default StudentManager;
